//
//  JCLLabel.swift
//  WeiBo
//
//  Created by DDC on 2017/9/26.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

class JCLLabel: UILabel {

       // 重写text属性来赋值
        override var text: String? {
            didSet {
                prepareTextContent()
            }
        }
        // 懒加载TextKit属性
        fileprivate lazy var textStorage = NSTextStorage()
        fileprivate lazy var textLayoutManager = NSLayoutManager()
        fileprivate lazy var textContainer = NSTextContainer()
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            prepareTextKit()
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            prepareTextKit()
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            textContainer.size = bounds.size
        }
        /// 绘制图形文字方法
        ///
        /// - Parameter rect: 文本属性
        override func drawText(in rect: CGRect) {
            
            let range = NSRange(location: 0, length: textStorage.length)
            textLayoutManager.drawBackground(forGlyphRange: range, at: CGPoint())
            textLayoutManager.drawGlyphs(forGlyphRange: range, at: CGPoint())
        }
        /// 获取点击位置的索引
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            guard let location = touches.first?.location(in: self) else {
                return
            }
            // 获取当前点击字符串的索引
            let idx = textLayoutManager.glyphIndex(for: location, in: textContainer)
            print(idx)
            // 判断索引是否在url点击的范围内
            for r in urlRanges ?? [] {
                
                if NSLocationInRange(idx, r) {
                    // 在url范围内
                    textStorage.addAttributes([NSForegroundColorAttributeName:UIColor.blue], range: r)
                    // 如果需要重绘, 需要实现setNeedsDisplay()这个方法,而不是drawRect!!!
                    setNeedsDisplay()
                }else {
                    // 不在范围内
                }
                
            }
            
        }
        
    }
    extension JCLLabel {
        func prepareTextKit()  {
            // 开启用户交互
            isUserInteractionEnabled = true
            // 准备文本内容
            prepareTextContent()
            
            textStorage.addLayoutManager(textLayoutManager)
            textLayoutManager.addTextContainer(textContainer)
            
        }
        /// 准备文本内容
        func prepareTextContent () {
            
            if attributedText != nil {
                textStorage.setAttributedString(attributedText!)
            } else if let text = text {
                textStorage.setAttributedString(NSAttributedString(string: text))
            } else {
                textStorage.setAttributedString(NSAttributedString(string: ""))
            }
            
            for r in urlRanges ?? [] {
                
                textStorage.addAttributes([NSForegroundColorAttributeName:UIColor.yellow,
                                           NSBackgroundColorAttributeName:UIColor.gray], range: r)
            }
            
        }
        
    }
    extension JCLLabel {
        
        var urlRanges :[NSRange]? {
            
            /// 网址的匹配样式
            let pattern = "[a-zA-Z]*://[a-zA-Z0-9/\\.]*"
            /// 创建正则表达式
            guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {
                return nil
            }
            /// 匹配内容
            let result = regx.matches(in: textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length))
            
            /// 设置空数组
            var ranges = [NSRange]()
            for r in result {
                
                ranges.append(r.rangeAt(0))
            }
            
            return ranges
        }
}
